package com.atguigu.spzx.manager.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.atguigu.spzx.manager.mapper.CategoryMapper;
import com.atguigu.spzx.model.vo.product.CategoryExcelVo;

import java.util.ArrayList;
import java.util.List;

public class ExcelListener<T> extends AnalysisEventListener<T> {

    private static final int BATCH_COUNT = 100; //批量处理数据的数量

    List<CategoryExcelVo> categoryExcelVoList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    CategoryMapper categoryMapper;

    public ExcelListener(CategoryMapper categoryMapper){
        this.categoryMapper = categoryMapper;
    }


    //Excel文件中每一行解析，invoke方法都会执行一次
    @Override
    public void invoke(T data, AnalysisContext context) {
        categoryExcelVoList.add((CategoryExcelVo)data);
        if(categoryExcelVoList.size() >= BATCH_COUNT){
            saveData();
            categoryExcelVoList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    public void saveData(){
        categoryMapper.saveBatch(categoryExcelVoList);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if(categoryExcelVoList.size() > 0){
            saveData();
        }
    }
}
